package com.cropdoctor.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.Result;
import com.cropdoctor.common.ResultCode;
import com.cropdoctor.mapper.SysUserRoleRelationMapper;
import com.cropdoctor.model.po.SysPermissionPo;
import com.cropdoctor.model.po.SysUserPo;
import com.cropdoctor.model.po.SysUserRoleRelationPo;
import com.cropdoctor.model.properties.WeChatProperties;
import com.cropdoctor.service.SysPermissionService;
import com.cropdoctor.service.SysUserService;
import com.cropdoctor.service.WeChatService;
import com.cropdoctor.util.ConvertUtils;
import com.cropdoctor.util.JwtTokenUtils;
import com.cropdoctor.util.WXUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Permissions;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    SysUserRoleRelationMapper sysUserRoleRelationMapper;

    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysPermissionService sysPermissionService;

    @Override
    @Transactional
    public Result<SysUserPo> login(JSONObject userInfo) {
        JSONObject jsonObject = WXUtils.authCode2Session(weChatProperties.getAppid(),
                weChatProperties.getSecret(),
                userInfo.getString("code"));

        if(jsonObject.get("errcode")!=null){
            //登录失败
            return Result.error(ResultCode.USER_LOGIN_FAIL);
        }
        //登录成功
        String openid = jsonObject.getString("openid");
        SysUserPo byOpenId = sysUserService.getByOpenId(openid); //根据openId查询数据库中是否有这个用户
        SysUserPo entity =null;
        if(byOpenId==null){//没有当前登录用户,保存新用户数据
            byOpenId = new SysUserPo();
            entity = userInfo2Entity(userInfo,byOpenId,openid,jsonObject);
            entity.setAvatarUrl("https://crop-doctor.oss-cn-beijing.aliyuncs.com/wechat/default_avater.png");//微信用户分配默认头像
            boolean save = sysUserService.save(byOpenId);//将数据存进数据库
            if(!save) return Result.error(ResultCode.USER_LOGIN_FAIL);

            SysUserRoleRelationPo sysUserRoleRelationPo = new SysUserRoleRelationPo();
            sysUserRoleRelationPo.setRoleId(2);
            sysUserRoleRelationPo.setUserId(byOpenId.getId());//将role和user对应到关系表中

            int insert = sysUserRoleRelationMapper.insert(sysUserRoleRelationPo);
            if(insert <= 0) return Result.error(ResultCode.USER_LOGIN_FAIL);
        }else {
            if("0".equals(byOpenId.getEnabled().toString())) return Result.error(ResultCode.USER_ACCOUNT_DISABLE);
            //更新数据
            entity = userInfo2Entity(userInfo,byOpenId,openid,jsonObject);

            boolean update = sysUserService.update(byOpenId,new LambdaQueryWrapper<SysUserPo>().eq(SysUserPo::getOpenid,openid));
            if(!update) return Result.error(ResultCode.USER_LOGIN_FAIL);
        }


        //生成令牌
        //将权限放/角色入token中
        String token = null;
        try {
            String permissions = "";
            List<SysPermissionPo> permissionList = sysPermissionService.selectListByUser(entity.getId());
            for (SysPermissionPo sysPermissionPo : permissionList) {
                if(sysPermissionPo != null) permissions += sysPermissionPo.getPermissionCode()+",";
            }
            permissions=permissions.substring(0, permissions.length()-1);//去除最后一个逗号
            token = JwtTokenUtils.createToken(entity.getId(),entity.getOpenid(),entity.getSessionKey(),permissions,entity.getAccount(),entity.getUserName());
            SysUserPo sysUserPo = ConvertUtils.sourceToTarget(byOpenId, SysUserPo.class);
            sysUserPo.setToken(JwtTokenUtils.TOKEN_PREFIX+token);
            return Result.success(sysUserPo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.USER_LOGIN_FAIL);
        }
    }

    private SysUserPo userInfo2Entity(JSONObject userInfo, SysUserPo byOpenId,String openid,JSONObject jsonObject) {
        //设置新数据
//        byOpenId.setAvatarUrl(userInfo.getString("avatarUrl"));
//        byOpenId.setUserName(userInfo.getString("nickName"));//暂时注释掉
//        byOpenId.setUserName("hsy");
        byOpenId.setAccount(openid);//微信端登录账号同openid 保证唯一性
        byOpenId.setOpenid(openid);
//        byOpenId.setUnionid(jsonObject.getString("unionid"));
        byOpenId.setSessionKey(jsonObject.getString("session_key"));
        byOpenId.setLastLoginTime(LocalDateTime.now());
//        byOpenId.setGender(userInfo.getIntValue("gender"));
//        byOpenId.setCountry(userInfo.getString("country"));
//        byOpenId.setProvince(userInfo.getString("province"));
//        byOpenId.setCity(userInfo.getString("city"));
        return byOpenId;
    }
}
